package com.htjc.integral.redpacket.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import com.commons.service.context.spring.config.CustomizedPropertyPlaceholderConfigurer;
import com.htjc.cht.api.util.DigitalSignTool;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

@Slf4j(topic="redpacketLogger")
@Service
public class HtjcSignToolManageK {
	private DigitalSignTool signerTool = null;
	private DigitalSignTool checkSignerTool = null;
	
	@Autowired
    private Environment env;

	private CustomizedPropertyPlaceholderConfigurer propConfig;

	public void setPropConfig(CustomizedPropertyPlaceholderConfigurer propConfig) {
		this.propConfig = propConfig;
	}

	public void init() {
		try {
			String path = java.net.URLDecoder.decode(HtjcSignToolManageK.class.getResource("/sign/").getPath(), "utf-8");// 证书路径
			String pfx_file = path + "shop.pfx"; // 商户证书路径
			log.info("pfx_file:"+pfx_file);
			String rootCertificatePath = path + "cacert.pem"; // 根证书路径
			log.info("rootCertificatePath:"+rootCertificatePath);
			
			String keyStorePassword =env.getProperty("sign.key.store.password");// 商户证书库密码
			
			log.info("keyStorePassword:"+keyStorePassword);
			String keyPassword =env.getProperty("sign.key.password");// 商户证书库私钥保护密码
			log.info("keyPassword:"+keyPassword);
			signerTool = DigitalSignTool.getSigner(pfx_file, keyStorePassword,keyPassword); // 签名工具实例
			checkSignerTool = DigitalSignTool.getVerifier(rootCertificatePath);// 验签工具实例
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 数据签名
	 * 
	 * @param orginalData
	 *            待签名数据
	 * @return 成功返回：签名数据；失败返回：null
	 */
	public String sign(String orginalData) {
		String signData = null;
		try {
			log.info("【输出原文orginalData：】"+orginalData);
			log.info("【输出signerTool】"+signerTool);
			signData = signerTool.sign(orginalData.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return signData;

	}

	/**
	 * 数据验签
	 * 
	 * @param signData
	 *            签名数据
	 * @param originalData
	 *            被签名数据
	 * @param dn
	 *            证书DN
	 * @throws Exception
	 *             签名失败抛出异常
	 */
	public void verifySign(String signData, String originalData, String dn)
			throws Exception {
		checkSignerTool.verify(signData, originalData.getBytes(), dn);
	}

}
